package com.geline.web.handler;

import com.geline.cloud.core.BaseSessionService;
import com.geline.web.annotation.AutoUserId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

@ControllerAdvice
public class AutoUserIdRequestBodyAdvice implements RequestBodyAdvice {

    @Autowired
    private BaseSessionService sessionService;

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter,
                                           Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (body != null) {
            Class<?> clazz = body.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(AutoUserId.class)) {
                    field.setAccessible(true);
                    try {
                        field.set(body, sessionService.getUserId());
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
                                  Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }
}
